package com.econ.powercloud.ems.timing.report.prometheus.callback;

import com.econ.powercloud.console.facade.utils.CacheKeyUtils;
import com.econ.powercloud.ems.common.util.JacksonExtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public abstract class AbstractPrometheusSingleDataCallback {

    private final static String INSTANCE_KEY = "data.result[0].metric.instance";

    private final static String VALUE_KEY = "data.result[0].value[1]";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    abstract String getCategory();

    abstract String getItem();

    public void dealWithPrometheusCallbackData(String content) {
        Map<String, String> prometheusResult = JacksonExtUtil.flatJsonToMap(content);
        if(!prometheusResult.containsKey(INSTANCE_KEY) || !prometheusResult.containsKey(VALUE_KEY)){
            return;
        }
        String instance = (String)prometheusResult.get(INSTANCE_KEY).replaceAll(":", "-");
        String value = prometheusResult.get(VALUE_KEY);
        String redisKey = CacheKeyUtils.getMonitorDataKey(instance, getCategory());
        HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
        hashOperations.put(redisKey, getItem(), value);
    }
}
